package com.demo.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @Project: 新一代清算系统
 * @Description: 中文类名。
 *               类功能简介。
 * @Version 1.0.0
 * @Author
 *         <li>2019-01-21 huangbw13744@hundsun.com Create 1.0
 * @Copyright ©2017-2019 中央结算公司，版权所有。
 */
public class CreateModuleConfig
{
    /** ares根目录，从config配置获取 */
    static String       PATH       = "";
    /** 数据库目录 */
    static final String MODULE     = "database\\";
    /** 子系统简称，从config配置获取 */
    static String       SYSTEMNAME = "";
    
    static final List<String> packList = new ArrayList<>();
    
    static final List<Map<String, Object>> list = new ArrayList<>();
    
    static Properties properties = new Properties();
    
    static final String separator = "/";
    
    /**
     * 功能描述
     *
     * @param args
     */
    public static void main(String[] args)
    {
        readConfig();
        StringBuffer sb = new StringBuffer();
        readFile(PATH + MODULE + SYSTEMNAME + "\\");
        sb.append("<root>").append("\r\n");
        for (String packName : packList) {
            sb.append("    <packageNode packageName=\"" + packName + "\">").append("\r\n");
            List<Map<String, Object>> resList = list.stream().filter(map -> map.get("package").equals(packName))
                .collect(Collectors.toList());
            for (Map<String, Object> map : resList) {
                sb.append(
                    "        <table tableName=\"" + map.get("table") + "\"></table><!--" + map.get("cName") + " -->")
                    .append("\r\n");
            }
            sb.append("    </packageNode>").append("\r\n");
        }
        sb.append("</root>");
        createFile(sb);
    }
    
    private static void readFile(String path)
    {
        File file = new File(path);
        if (file.getName().endsWith(".svn")) {
            return;
        }
        List<File> list = Arrays.asList(file.listFiles());
        for (File f : list) {
            if (f.isDirectory()) {
                readFile(f.getPath());
            }
            if (!f.getName().endsWith(".table")) {
                continue;
            }
            String filePath = formatPath(f.getPath());
            String rootPath = formatPath(PATH + MODULE + SYSTEMNAME + separator);
            if (!packList.contains(filePath.replace(rootPath, "").split(separator)[0])) {
                packList.add(filePath.replace(rootPath, "").split(separator)[0]);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("package", filePath.replace(rootPath, "").split(separator)[0]);
            map.put("table", filePath.replace(rootPath, "").split(separator)[1].replace(".table", ""));
            readTableCNName(filePath, map);
        }
    }
    
    private static void readTableCNName(String path, Map<String, Object> map)
    {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(new FileInputStream(new File(path)));
            Element root = document.getRootElement();
            Attribute name = root.attribute("chineseName");
            map.put("cName", name.getValue());
            list.add(map);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static void readConfig()
    {
        try {
            InputStream inputStream = CreateModuleConfig.class.getClassLoader()
                .getResourceAsStream("config/config.properties");
            properties = new Properties();
            properties.load(inputStream);
            SYSTEMNAME = properties.get("sub_system_name").toString().toUpperCase();
            PATH = properties.getProperty("ares_path").toString();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    private static void createFile(StringBuffer sb)
    {
        try {
            String path = System.getProperty("user.dir") + "/src/main/resources/config/" + SYSTEMNAME
                          + "ModuleConfig.xml";
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file));
            writer.write(sb.toString());
            writer.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static String formatPath(String path)
    {
        return path.replaceAll("\\\\", separator);
    }
    
}
